package com.wdl.report.business.search.mvp.ui.activity;

import android.app.Activity;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;

import com.afollestad.materialdialogs.GravityEnum;
import com.afollestad.materialdialogs.MaterialDialog;
import com.alibaba.android.arouter.facade.annotation.Route;
import com.bigkoo.pickerview.builder.TimePickerBuilder;
import com.bigkoo.pickerview.view.TimePickerView;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.jess.arms.base.BaseActivity;
import com.jess.arms.di.component.AppComponent;
import com.jess.arms.utils.ArmsUtils;

import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.footer.ClassicsFooter;
import com.scwang.smartrefresh.layout.header.ClassicsHeader;
import com.wdl.report.app.AppLifecyclesImpl;
import com.wdl.report.app.utils.pdf.PdfPrinter;
import com.wdl.report.business.search.di.component.DaggerReportSearchActivityComponent;
import com.wdl.report.business.search.mvp.contract.ReportSearchActivityContract;
import com.wdl.report.business.search.mvp.presenter.ReportSearchActivityPresenter;

import com.wdl.report.R;
import com.wdl.report.R2;
import com.wdl.report.business.search.mvp.ui.adapter.ReprotListAdapter;
import com.wdl.report.business.search.mvp.ui.adapter.SpaceItemDecoration;
import com.wdl.report.db.ReportInfo;
import com.wdl.report.db.ReportInfoDBHelper;


import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;
import me.wdl.component.commonsdk.core.RouterHub;
import me.wdl.component.commonsdk.utils.Utils;

import static com.jess.arms.utils.Preconditions.checkNotNull;


/**
 * ================================================
 * Description:
 * <p>
 * Created by MVPArmsTemplate on 07/08/2019 12:52
 * <a href="mailto:jess.yan.effort@gmail.com">Contact me</a>
 * <a href="https://github.com/JessYanCoding">Follow me</a>
 * <a href="https://github.com/JessYanCoding/MVPArms">Star me</a>
 * <a href="https://github.com/JessYanCoding/MVPArms/wiki">See me</a>
 * <a href="https://github.com/JessYanCoding/MVPArmsTemplate">模版请保持更新</a>
 * ================================================
 */
@Route(path = RouterHub.REPORT_SEARCHACTIVITY)
public class ReportSearchActivityActivity extends BaseActivity<ReportSearchActivityPresenter> implements ReportSearchActivityContract.View {

    @BindView(R2.id.search_name)
    EditText et_name;

    @BindView(R2.id.history_list)
    RecyclerView list_viwe;

    @BindView(R2.id.refresh)
    SmartRefreshLayout refreshLayout;

    @BindView(R2.id.start_time)
    TextView tv_start_time;

    @BindView(R2.id.end_time)
    TextView tv_end_time;

    private ReportInfo curReportInfo = null;

    private ReprotListAdapter reprotListAdapter;

    private int curPage = 0;
    private int pageSize = 30;

    private Date startTime = null, endTime = null;

    @Override
    public void setupActivityComponent(@NonNull AppComponent appComponent) {
        DaggerReportSearchActivityComponent //如找不到该类,请编译一下项目
                .builder()
                .appComponent(appComponent)
                .view(this)
                .build()
                .inject(this);
    }

    @OnClick(R2.id.start_time)
    public void clickStart(View view) {
        showTimeType = 1;
        showTimeView();
    }

    @OnClick(R2.id.end_time)
    public void clickEnd(View view) {
        showTimeType = 2;
        showTimeView();
    }

    @OnClick(R2.id.search_go)
    public void clickGo(View view) {
        curPage = 0;
        loadData();
    }

    @OnClick(R2.id.search_clear)
    public void clickClear(View view) {
        tv_start_time.setText("开始时间");
        tv_end_time.setText("结束时间");
        et_name.setText("");
        startTime = null;
        endTime = null;

        curPage = 0;
        loadData();
    }

    @Override
    public int initView(@Nullable Bundle savedInstanceState) {
        return R.layout.activity_search_report; //如果你不需要框架帮你设置 setContentView(id) 需要自行设置,请返回 0
    }

    @Override
    public void initData(@Nullable Bundle savedInstanceState) {
        list_viwe.setLayoutManager(new LinearLayoutManager(this));
        list_viwe.addItemDecoration(new SpaceItemDecoration(35));

        reprotListAdapter = new ReprotListAdapter(R.layout.item_history_report, new ArrayList<>());
        list_viwe.setAdapter(reprotListAdapter);

        reprotListAdapter.setOnItemClickListener((adapter, view, position) -> {
            curReportInfo = (ReportInfo) adapter.getData().get(position);

            showChooseModel();
        });

        refreshLayout.setEnableRefresh(true);
        refreshLayout.setEnableLoadMore(true);
        refreshLayout.setRefreshHeader(new ClassicsHeader(this));//设置Header
        refreshLayout.setRefreshFooter(new ClassicsFooter(this));//设置Footer
        refreshLayout.setOnRefreshListener(refreshLayout -> {
            curPage = 0;
            loadData();
        });

        refreshLayout.setOnLoadMoreListener(refreshLayout -> {
            curPage++;
            loadData();
        });

        loadData();
    }

    private void loadData() {
        refreshLayout.finishRefresh();

        if (curPage == 0) {
            reprotListAdapter.getData().clear();
        }

        String name = et_name.getText().toString().trim();

        name = name == null || name.length() < 1 ? null : name;

        List<ReportInfo> reportInfos = ReportInfoDBHelper.searchList(null, name, startTime, endTime, curPage, pageSize);
        reprotListAdapter.addData(reportInfos);
        reprotListAdapter.notifyDataSetChanged();

        if (reportInfos.size() < pageSize) {
            refreshLayout.finishLoadMore();
        }
    }

    @Override
    public void showLoading() {

    }

    @Override
    public void hideLoading() {

    }

    @Override
    public void showMessage(@NonNull String message) {
        checkNotNull(message);
        ArmsUtils.snackbarText(message);
    }

    @Override
    public void launchActivity(@NonNull Intent intent) {
        checkNotNull(intent);
        ArmsUtils.startActivity(intent);
    }

    @Override
    public void killMyself() {
        finish();
    }

    private TimePickerView pvTime;
    private int showTimeType;

    private void showTimeView() {
        if (pvTime == null) {
            pvTime = new TimePickerBuilder(ReportSearchActivityActivity.this, (date, v) -> {
                SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
                String dateFormat = format.format(date);
                if (showTimeType == 1) {
                    startTime = date;
                    tv_start_time.setText(dateFormat);
                } else {
                    endTime = date;
                    tv_end_time.setText(dateFormat);
                }
            }).build();
        }

        pvTime.show();
    }

    private MaterialDialog mMaterialDialog = null;
    private String[] stocks = {"预览", "打印"};

    private void showChooseModel() {
        if (mMaterialDialog == null) {
            MaterialDialog.Builder mBuilder = new MaterialDialog.Builder(ReportSearchActivityActivity.this);
            mBuilder.title("请选择操作");
            mBuilder.titleGravity(GravityEnum.CENTER);
            mBuilder.titleColor(Color.parseColor("#000000"));
            mBuilder.items(stocks);
            mBuilder.autoDismiss(true);
            mBuilder.itemsCallback((dialog, itemView, position, text) -> {
                if ("预览".equals(text)) {
                    AppLifecyclesImpl.showPdfUrl = curReportInfo.getPdfPath();
                    Utils.navigation(ReportSearchActivityActivity.this, RouterHub.REPORT_SHOWPDFACTIVITY);
                } else if ("打印".equals(text)) {
                    PdfPrinter.doPdfPrint(ReportSearchActivityActivity.this, curReportInfo.getPdfPath());
                }
            });
            mMaterialDialog = mBuilder.build();
        }
        mMaterialDialog.show();
    }
}
